package org.jeecg.modules.app.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.node.ForestNodeMerger;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.app.entity.AppClient;
import org.jeecg.modules.app.entity.AppClientMenu;
import org.jeecg.modules.app.entity.AppMenu;
import org.jeecg.modules.app.service.IAppClientMenuService;
import org.jeecg.modules.app.service.IAppClientService;
import org.jeecg.modules.app.service.IAppMenuService;
import org.jeecg.modules.app.vo.MenuTreeVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 应用菜单
 * @Author: sean
 * @Date:   2024-10-25
 * @Version: V1.0
 */
@Api(tags="应用菜单")
@RestController
@RequestMapping("/app/menu")
@Slf4j
@RequiredArgsConstructor
public class AppMenuController extends JeecgController<AppMenu, IAppMenuService> {

	private final IAppMenuService appMenuService;
	private final IAppClientService appClientService;
	private final IAppClientMenuService appClientMenuService;
	
	/**
	 * 分页列表查询
	 *
	 * @param appMenu
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	//@AutoLog(value = "应用菜单-分页列表查询")
	@ApiOperation(value="应用菜单-分页列表查询", notes="应用菜单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AppMenu>> queryPageList(AppMenu appMenu, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
												@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
												HttpServletRequest request) {
		QueryWrapper<AppMenu> queryWrapper = QueryGenerator.initQueryWrapper(appMenu, request.getParameterMap());
		Page<AppMenu> page = new Page<>(pageNo, pageSize);
		IPage<AppMenu> pageList = appMenuService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 加载数据节点
	 *
	 * @return
	 */
	@ApiOperation(value="租车菜单-树形列表查询", notes="租车菜单-树形列表查询")
	@RequestMapping(value = "/tree", method = RequestMethod.GET)
	public Result<Map> list(AppMenu appMenu, HttpServletRequest request) {
		QueryWrapper<AppMenu> queryWrapper = QueryGenerator.initQueryWrapper(appMenu, request.getParameterMap());
		List<MenuTreeVO> listResult = appMenuService.selectJoinTree(queryWrapper);
		List<String> ids = listResult.stream().map(MenuTreeVO::getId).collect(Collectors.toList());
		List<MenuTreeVO> treeList = ForestNodeMerger.merge(listResult);
		Map map	= new HashMap();
		map.put("ids",ids);
		map.put("treeList",treeList);
		return Result.OK(map);
	}

	/**
	 * 查询应用菜单
	 * @return
	 */
	@RequestMapping(value = "/query-client-menu", method = RequestMethod.GET)
	public Result<List<String>> queryClientMenu(@RequestParam(name = "clientId", required = true) String clientId) {
		Result<List<String>> result = new Result<>();
		try {
			List<AppClientMenu> list = appClientMenuService.list(new QueryWrapper<AppClientMenu>().lambda().eq(AppClientMenu::getClientId, clientId));
			result.setResult(list.stream().map(AppClientMenu -> String.valueOf(AppClientMenu.getMenuId())).collect(Collectors.toList()));
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 查询应用菜单
	 * @return
	 */
	@RequestMapping(value = "/client-menu", method = RequestMethod.GET)
	public Result<List<String>> clientMenu(@RequestParam(name = "code", required = true) String code) {
		Result<List<String>> result = new Result<>();
		try {
			AppClient appClient = appClientService.getOne(new QueryWrapper<AppClient>().eq("code", code));
			if(ObjectUtil.isNotEmpty(appClient)){
				List<AppClientMenu> list = appClientMenuService.list(new QueryWrapper<AppClientMenu>().lambda().eq(AppClientMenu::getClientId, appClient.getId()));
				Set<Long> menuIds = list.stream().map(AppClientMenu::getMenuId).collect(Collectors.toSet());
				List<AppMenu> appMenuList = appMenuService.listByIds(menuIds);
				result.setResult(appMenuList.stream().map(AppMenu -> String.valueOf(AppMenu.getCode())).collect(Collectors.toList()));
			}
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}


	/**
	 * 保存角色授权
	 *
	 * @return
	 */
	@RequestMapping(value = "/save-client-menu", method = RequestMethod.POST)
	public Result<String> saveClientMenu(@RequestBody JSONObject json) {
		long start = System.currentTimeMillis();
		Result<String> result = new Result<>();
		try {
			String clientId = json.getString("clientId");
			String menuIds = json.getString("menuIds");
			appClientMenuService.saveClientMenu(clientId, menuIds);
			result.success("保存成功！");
		} catch (Exception e) {
			result.error500("授权失败！");
			log.error(e.getMessage(), e);
		}
		return result;
	}


	/**
	 *   添加
	 *
	 * @param appMenu
	 * @return
	 */
	@AutoLog(value = "应用菜单-添加")
	@ApiOperation(value="应用菜单-添加", notes="应用菜单-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody AppMenu appMenu) {
		appMenuService.save(appMenu);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param appMenu
	 * @return
	 */
	@AutoLog(value = "应用菜单-编辑")
	@ApiOperation(value="应用菜单-编辑", notes="应用菜单-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody AppMenu appMenu) {
		appMenuService.updateById(appMenu);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "应用菜单-通过id删除")
	@ApiOperation(value="应用菜单-通过id删除", notes="应用菜单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		appMenuService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "应用菜单-批量删除")
	@ApiOperation(value="应用菜单-批量删除", notes="应用菜单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.appMenuService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "应用菜单-通过id查询")
	@ApiOperation(value="应用菜单-通过id查询", notes="应用菜单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AppMenu> queryById(@RequestParam(name="id",required=true) String id) {
		AppMenu appMenu = appMenuService.getById(id);
		if(appMenu==null) {
			return Result.error("未找到对应数据",null);
		}
		return Result.OK(appMenu);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param appMenu
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AppMenu appMenu) {
        return super.exportXls(request, appMenu, AppMenu.class, "应用菜单");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AppMenu.class);
    }

}
